import com.sun.jdi.DoubleType;

import java.io.*;
import java.net.*;
import java.util.Scanner;

public class Customer {
    private Socket socket;

    private PrintWriter out;

    private BufferedReader in;

    private static boolean connected = false;

    private static final String SERVER_HOST = "localhost";

    private static final int SERVER_PORT = 8080;

    private static final Scanner scanner;

    static {
        scanner = new Scanner(System.in);
    }

    public static void main(String[] args) {
        Customer customer = new Customer();
        customer.start();
    }

    public void start() {
        try {
            System.out.println("Connecting to Virtual Caffee...");
            socket = new Socket(SERVER_HOST, SERVER_PORT);
            out = new PrintWriter(socket.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            connected = true;
            System.out.println("Connected to Virtual Caffee!");

            // 启动消息监听线程
            Thread messageListener = new Thread(this::listenForMessages);
            messageListener.setDaemon(true);
            messageListener.start();
            printMenu();
            // 处理用户输入
            handleUserInput();

        } catch (IOException e) {
            System.err.println("❌ Failed to connect to server: " + e.getMessage());
        } finally {
            cleanup();
        }
    }

    private void listenForMessages() {
        try {
            String serverMessage;
            while (connected && (serverMessage = in.readLine()) != null) {
                System.out.println("🏪 " + serverMessage);
            }
        } catch (IOException e) {
            if (connected) {
                System.err.println("❌ Connection to server lost");
            }
        }
    }

    private static void printMenu() {
        System.out.println("\n💡 Available commands:");
        System.out.println("  order X tea/coffee      - Place an order");
        System.out.println("  order X teas and Y coffees - Order multiple drinks");
        System.out.println("  order status            - Check order status");
        System.out.println("  collect                 - Collect your order");
        System.out.println("  exit                    - Leave the caffee");
        System.out.println("----------------------------------------");
        System.out.println("Welcome to Virtual Caffee! Please enter your name:");
    }

    private void handleUserInput() {
        while (connected && scanner.hasNextLine()) {
            String userInput = scanner.nextLine().trim();
            if (userInput.equalsIgnoreCase("exit")) {
                out.println("exit");
                break;
            } else {
                out.println(userInput);
            }
        }
    }

    private void cleanup() {
        connected = false;
        try {
            if (out != null) out.close();
            if (in != null) in.close();
            if (socket != null) socket.close();
            if (scanner != null) scanner.close();
        } catch (IOException e) {
            System.err.println("Error during cleanup: " + e.getMessage());
        }
        System.out.println("👋 Disconnected from Virtual Caffee. Goodbye!");
    }

    // 优雅处理Ctrl-C退出
    static {
        Runtime
                .getRuntime()
                .addShutdownHook(new Thread(() -> System.out.println("\n⚠️  Interrupted! Closing connection...")));
    }
}